<?php
/**
 * 微信公众号管理页面类
 */
class HYWL_Wechat_Admin {
    
    private $options;
    private $logger;
    
    /**
     * 构造函数
     */
    public function __construct() {
        $this->options = get_option('hywl_wechat_options', array());
        $this->logger = new HYWL_Wechat_Logger();
    }
    
    /**
     * 初始化管理页面
     */
    public function init() {
        // 添加菜单
        add_action('admin_menu', array($this, 'add_menu_page'));
        
        // 注册设置
        add_action('admin_init', array($this, 'register_settings'));
        
        // 添加AJAX处理
        add_action('wp_ajax_hywl_wechat_view_log', array($this, 'ajax_view_log'));
    }
    
    /**
     * 添加菜单页面
     */
    public function add_menu_page() {
        add_menu_page(
            '微信公众号设置', 
            '微信公众号', 
            'manage_options', 
            'hywl-wechat', 
            array($this, 'render_settings_page'),
            'dashicons-smartphone', 
            100
        );
        
        // 添加日志子菜单
        add_submenu_page(
            'hywl-wechat',
            '微信日志', 
            '微信日志', 
            'manage_options', 
            'hywl-wechat-logs', 
            array($this, 'render_logs_page')
        );
    }
    
    /**
     * 注册设置
     */
    public function register_settings() {
        register_setting('hywl_wechat_options_group', 'hywl_wechat_options', array($this, 'sanitize_options'));
        
        // 基本设置
        add_settings_section(
            'hywl_wechat_basic_section',
            '基本设置',
            array($this, 'section_callback'),
            'hywl-wechat'
        );
        
        // 添加字段
        add_settings_field(
            'token',
            '接口验证Token',
            array($this, 'token_callback'),
            'hywl-wechat',
            'hywl_wechat_basic_section'
        );
        
        add_settings_field(
            'appid',
            'AppID',
            array($this, 'appid_callback'),
            'hywl-wechat',
            'hywl_wechat_basic_section'
        );
        
        add_settings_field(
            'appsecret',
            'AppSecret',
            array($this, 'appsecret_callback'),
            'hywl-wechat',
            'hywl_wechat_basic_section'
        );
        
        // 消息设置
        add_settings_section(
            'hywl_wechat_message_section',
            '消息设置',
            array($this, 'section_callback'),
            'hywl-wechat'
        );
        
        // 日志设置
        add_settings_section(
            'hywl_wechat_log_section',
            '日志设置',
            array($this, 'section_callback'),
            'hywl-wechat'
        );
        
        add_settings_field(
            'welcome_msg',
            '欢迎消息',
            array($this, 'welcome_msg_callback'),
            'hywl-wechat',
            'hywl_wechat_message_section'
        );
        
        add_settings_field(
            'not_found_msg',
            '未找到内容提示',
            array($this, 'not_found_msg_callback'),
            'hywl-wechat',
            'hywl_wechat_message_section'
        );
        
        add_settings_field(
            'search_limit',
            '搜索结果数量',
            array($this, 'search_limit_callback'),
            'hywl-wechat',
            'hywl_wechat_message_section'
        );
        
        // 日志设置字段
        add_settings_field(
            'log_enabled',
            '启用日志',
            array($this, 'log_enabled_callback'),
            'hywl-wechat',
            'hywl_wechat_log_section'
        );
        
        add_settings_field(
            'max_log_size',
            '单个日志文件大小限制',
            array($this, 'max_log_size_callback'),
            'hywl-wechat',
            'hywl_wechat_log_section'
        );
    }
    
    /**
     * 验证设置
     */
    public function sanitize_options($input) {
        $sanitized_input = array();
        
        // 验证Token
        if (isset($input['token'])) {
            $sanitized_input['token'] = sanitize_text_field($input['token']);
        }
        
        // 验证AppID
        if (isset($input['appid'])) {
            $sanitized_input['appid'] = sanitize_text_field($input['appid']);
        }
        
        // 验证AppSecret
        if (isset($input['appsecret'])) {
            $sanitized_input['appsecret'] = sanitize_text_field($input['appsecret']);
        }
        
        // 验证欢迎消息
        if (isset($input['welcome_msg'])) {
            $sanitized_input['welcome_msg'] = sanitize_textarea_field($input['welcome_msg']);
        }
        
        // 验证未找到内容提示
        if (isset($input['not_found_msg'])) {
            $sanitized_input['not_found_msg'] = sanitize_textarea_field($input['not_found_msg']);
        }
        
        // 验证搜索结果数量
        if (isset($input['search_limit'])) {
            $sanitized_input['search_limit'] = intval($input['search_limit']);
            if ($sanitized_input['search_limit'] < 1) {
                $sanitized_input['search_limit'] = 1;
            } elseif ($sanitized_input['search_limit'] > 8) {
                $sanitized_input['search_limit'] = 8;
            }
        }
        
        // 验证日志设置
        $sanitized_input['log_enabled'] = isset($input['log_enabled']) ? 1 : 0;
        
        // 验证日志文件大小限制
        if (isset($input['max_log_size'])) {
            $sanitized_input['max_log_size'] = intval($input['max_log_size']);
            if ($sanitized_input['max_log_size'] < 1) {
                $sanitized_input['max_log_size'] = 1;
            } elseif ($sanitized_input['max_log_size'] > 50) {
                $sanitized_input['max_log_size'] = 50;
            }
        }
        
        return $sanitized_input;
    }
    
    /**
     * 渲染设置页面
     */
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1>微信公众号设置</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('hywl_wechat_options_group');
                do_settings_sections('hywl-wechat');
                submit_button();
                ?>
                
                <hr>
                <h2>微信公众号配置说明</h2>
                <p>请按照以下步骤配置您的微信公众号：</p>
                <ol>
                    <li>登录微信公众平台，进入"开发 -> 基本配置"页面</li>
                    <li>将服务器地址(URL)设置为：<code><?php echo home_url('/wechat-api/'); ?></code></li>
                    <li>将Token设置为与上面配置相同的值</li>
                    <li>消息加解密方式选择"明文模式"</li>
                    <li>点击"启用"按钮</li>
                </ol>
                
                <h3>功能说明</h3>
                <p>用户可以在微信公众号中发送关键词，系统会自动搜索网站中相关的文章并返回搜索结果。</p>
            </form>
        </div>
        <?php
    }
    
    /**
     * 节回调函数
     */
    public function section_callback($args) {
        // 节说明
    }
    
    /**
     * Token回调函数
     */
    public function token_callback() {
        $token = isset($this->options['token']) ? $this->options['token'] : '';
        echo '<input type="text" id="token" name="hywl_wechat_options[token]" value="' . esc_attr($token) . '" class="regular-text" />';
        echo '<p class="description">用于微信服务器验证，请勿随意修改</p>';
    }
    
    /**
     * AppID回调函数
     */
    public function appid_callback() {
        $appid = isset($this->options['appid']) ? $this->options['appid'] : '';
        echo '<input type="text" id="appid" name="hywl_wechat_options[appid]" value="' . esc_attr($appid) . '" class="regular-text" />';
        echo '<p class="description">微信公众号的AppID</p>';
    }
    
    /**
     * AppSecret回调函数
     */
    public function appsecret_callback() {
        $appsecret = isset($this->options['appsecret']) ? $this->options['appsecret'] : '';
        echo '<input type="text" id="appsecret" name="hywl_wechat_options[appsecret]" value="' . esc_attr($appsecret) . '" class="regular-text" />';
        echo '<p class="description">微信公众号的AppSecret</p>';
    }
    
    /**
     * 欢迎消息回调函数
     */
    public function welcome_msg_callback() {
        $welcome_msg = isset($this->options['welcome_msg']) ? $this->options['welcome_msg'] : '';
        echo '<textarea id="welcome_msg" name="hywl_wechat_options[welcome_msg]" rows="3" class="large-text">' . esc_textarea($welcome_msg) . '</textarea>';
        echo '<p class="description">用户关注公众号时发送的欢迎消息</p>';
    }
    
    /**
     * 未找到内容提示回调函数
     */
    public function not_found_msg_callback() {
        $not_found_msg = isset($this->options['not_found_msg']) ? $this->options['not_found_msg'] : '';
        echo '<textarea id="not_found_msg" name="hywl_wechat_options[not_found_msg]" rows="3" class="large-text">' . esc_textarea($not_found_msg) . '</textarea>';
        echo '<p class="description">未找到相关内容时的提示消息</p>';
    }
    
    /**
     * 搜索结果数量回调函数
     */
    public function search_limit_callback() {
        $search_limit = isset($this->options['search_limit']) ? intval($this->options['search_limit']) : 5;
        echo '<input type="number" id="search_limit" name="hywl_wechat_options[search_limit]" value="' . esc_attr($search_limit) . '" min="1" max="8" />';
        echo '<p class="description">搜索结果返回的文章数量（最多8篇）</p>';
    }
    
    /**
     * 启用日志回调函数
     */
    public function log_enabled_callback() {
        $log_enabled = isset($this->options['log_enabled']) ? $this->options['log_enabled'] : 0;
        echo '<label><input type="checkbox" id="log_enabled" name="hywl_wechat_options[log_enabled]" value="1"' . checked(1, $log_enabled, false) . ' /> 启用日志记录</label>';
        echo '<p class="description">记录微信公众号接口的请求和响应日志，有助于调试和监控。</p>';
    }
    
    /**
     * 日志文件大小限制回调函数
     */
    public function max_log_size_callback() {
        $max_log_size = isset($this->options['max_log_size']) ? intval($this->options['max_log_size']) : 5;
        echo '<input type="number" id="max_log_size" name="hywl_wechat_options[max_log_size]" value="' . esc_attr($max_log_size) . '" min="1" max="50" /> MB';
        echo '<p class="description">单个日志文件的最大大小，超过该大小后会创建新的日志文件。</p>';
    }
    
    /**
     * 渲染日志页面
     */
    public function render_logs_page() {
        // 检查是否启用了日志
        $log_enabled = isset($this->options['log_enabled']) ? $this->options['log_enabled'] : 0;
        
        ?>
        <div class="wrap">
            <h1>微信公众号日志</h1>
            
            <?php if (!$log_enabled): ?>
                <div class="notice notice-warning">
                    <p>日志功能当前未启用。请在<a href="<?php echo admin_url('admin.php?page=hywl-wechat'); ?>">微信公众号设置</a>中启用日志功能。</p>
                </div>
            <?php endif; ?>
            
            <div id="log-viewer-container">
                <div class="log-viewer-header">
                    <h2>日志文件列表</h2>
                    <?php
                    $log_files = $this->logger->get_log_files();
                    if (empty($log_files)) {
                        echo '<p>暂无日志文件。</p>';
                    } else {
                        echo '<table class="wp-list-table widefat fixed striped">';
                        echo '<thead><tr><th>文件名</th><th>大小</th><th>日期</th><th>操作</th></tr></thead>';
                        echo '<tbody>';
                        foreach ($log_files as $log) {
                            echo '<tr>';
                            echo '<td>' . esc_html($log['file']) . '</td>';
                            echo '<td>' . esc_html($log['size']) . '</td>';
                            echo '<td>' . esc_html($log['date']) . '</td>';
                            echo '<td><a href="#" class="button view-log" data-file="' . esc_attr($log['file']) . '">查看</a></td>';
                            echo '</tr>';
                        }
                        echo '</tbody>';
                        echo '</table>';
                    }
                    ?>
                </div>
                
                <div class="log-viewer-content" style="margin-top: 20px;">
                    <h2>日志内容</h2>
                    <div id="log-content" style="background: #f0f0f1; padding: 10px; border: 1px solid #ccc; height: 500px; overflow: auto; font-family: monospace; white-space: pre; font-size: 12px;">
                        选择上方的日志文件进行查看...
                    </div>
                </div>
            </div>
            
            <script type="text/javascript">
            jQuery(document).ready(function($) {
                $('.view-log').on('click', function(e) {
                    e.preventDefault();
                    var logFile = $(this).data('file');
                    var logContent = $('#log-content');
                    
                    logContent.html('正在加载日志...');
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'hywl_wechat_view_log',
                            file: logFile,
                            _wpnonce: '<?php echo wp_create_nonce('hywl_wechat_view_log'); ?>'
                        },
                        success: function(response) {
                            logContent.html(response);
                        },
                        error: function() {
                            logContent.html('加载日志失败，请重试。');
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }
    
    /**
     * AJAX处理查看日志
     */
    public function ajax_view_log() {
        // 安全检查
        if (!current_user_can('manage_options')) {
            wp_die('无权限访问');
        }
        
        check_ajax_referer('hywl_wechat_view_log');
        
        $file = isset($_POST['file']) ? sanitize_text_field($_POST['file']) : '';
        if (empty($file)) {
            echo '未指定日志文件';
            wp_die();
        }
        
        $log_content = $this->logger->get_log_content($file);
        if (empty($log_content)) {
            echo '日志为空或文件不存在';
        } else {
            echo htmlspecialchars($log_content);
        }
        
        wp_die();
    }
} 